package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    BookService bookService;

    /**
     * 分页查询书籍
     * @param pageNum
     * @param pageSize
     * @param name
     * @param author
     * @return
     */
    @GetMapping("/selectBook")
    public Result<?> selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(defaultValue = "") String name,
                                @RequestParam(defaultValue = "") String author){
        IPage<Book> BookPage = bookService.selectPage(pageNum,pageSize,name,author);
        return Result.success(BookPage);
    }

    /**
     * 新增书籍
     * @param book
     * @return
     */
    @PostMapping("/addBook")
    public Result<?> save(@RequestBody Book book){
        if (book.getName() == null || book.getAuthor() == null || book.getPrice() == null || book.getPublishTime()== null){
            return Result.error("4001","所填字段不能为空,新增失败！");
        }
        bookService.addBook(book);
        return Result.success();
    }

    /**
     * 更新书籍信息
     * @param book
     * @return
     */
    @PutMapping("/updateBook")
    public Result<?> update(@RequestBody Book book){
        if (book.getName() == null || book.getAuthor() == null || book.getPrice() == null || book.getPublishTime()== null){
            return Result.error("4001","所填字段不能为空,更新失败！");
        }
        bookService.updateBook(book);
        return Result.success();
    }

    /**
     * 删除书籍
     * @param bookId
     * @return
     */
    @GetMapping("/deleteBook")
    public Result<?> delete(@RequestParam int bookId){
        bookService.deleteBook(bookId);
        return  Result.success();
    }

    @GetMapping("/selectBookByUserId")
    public Result<?> selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(defaultValue = "") Integer userId){
        IPage<Book> bookPage = bookService.selectBookByUserId(pageNum,pageSize,userId);
        return Result.success(bookPage);
    }
}
